package com.zhang;

import java.util.NoSuchElementException;

public class MyLinkedList<E> {
    private Node first;
    private Node last;
    private int size;

    public void add(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null) {
            first = newNode;
        } else {
            l.next = newNode;
        }
        size++;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        if (first == null) {
            return sb.append("]").toString();
        }
        Node forNode = first;
        for (int i = 0; i < size; i++) {
            if (i == size - 1) {
                sb.append(forNode.data + "]");
            } else {
                sb.append(forNode.data + ",");
            }
            forNode = next(forNode);
        }
        return sb.toString();
    }

    public boolean remove(E e) {
        int index = -1;
        Node forNode = first;
        if (forNode == null)
            throw new NoSuchElementException("当前集合为空！");
        for (int i = 0; i < size; i++) {
            if (forNode.data.equals(e)) {
                index = i;
                break;
            }
            forNode = next(forNode);
        }
        if (index == -1)
            return false;
        fastRemove(index);
        return true;
    }

    private void fastRemove(int index) {
        if (index == 0) {
            removeFirst();
            return;
        }
        if (index == size - 1) {
            removeLast();
            return;
        }
        if (index < 0 || index > size - 1) {
            throw new NoSuchElementException("没有这个元素: " + index);
        }
        Node delete = first;
        for (int i = 0; i < index; i++) {
            delete = delete.next;
        }
        //循环结束后，找到要删除的节点
        System.out.println("删除的元素" + delete.data);
        Node pre = delete.pre;
        Node next = delete.next;
        pre.next = next;
        next.pre = next;
        delete = null;
        size--;

    }

    private void removeLast() {
        Node<E> pre = this.last.pre;
        pre.next = null;
        last = pre;
        size--;
    }

    private void removeFirst() {
        Node<E> next = first.next;
        next.pre = null;
        this.first = next;
        size--;
    }

    public Node next(Node node) {
        return node == null ? null : node.next;
    }

    private class Node<E> {
        Node<E> pre;
        E data;
        Node<E> next;

        @Override
        public String toString() {
            return "Node{" +
                    "data=" + data +
                    '}';
        }

        public Node(Node<E> pre, E data, Node<E> next) {
            this.pre = pre;
            this.data = data;
            this.next = next;
        }
    }
}
